<?php

use Biz\service\NewProduct\NewProductService;

/**
 * Description: 获取新品速递统计
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/5/21
 * Time: 11:12
 */
class GetStatisticsDataAction extends ActionPlugin
{
    public const USER_LEVEL = self::LEVEL_REGISTER;

    /**
     * @throws Exception
     */
    public function main()
    {
        $nid = $this->getRequest()->getPost('nid', 0);
        $uid = $this->uid;
        if (!$nid || !$uid) {
            throw new Exception("非法传参");
        }
        $data = [];

        //获取参加活动记录
        $join_record = NewProductService::getJoinRecordData($nid);
        if (!$join_record) {
            $data['msg'] = '暂无参加活动记录';
            return $this->setSuccess($data, 0);
        }
        $join_record = array_column($join_record, null, 'tid');

        //获取参加总人数
        $get_all_person = NewProductService::getJoinUserCount($nid);
        if (!$get_all_person) {
            $data['msg'] = '暂无参加活动记录';
            return $this->setSuccess($data, 0);
        }
        $all_person_num = array_sum(array_column($get_all_person, 'p_num'));
        //获取活动标签
        $tag_list = NewProductService::getTagsByNid([$nid]);
        if (!$tag_list) {
            $data['msg'] = '暂无参加活动记录';
            return $this->setSuccess($data, 0);
        }
        $tag_list = array_column($tag_list, 'tag', 'id');

        //查询当前用户参加的记录
        $tid = NewProductService::getRecordForUser($uid, $nid);

        if (!$tid) {
            $data['msg'] = '暂无参加活动记录';
            return $this->setSuccess($data, 0);
        }
        //计算百分比
        foreach ($tag_list as $k => $v) {
            $percentage = 0;
            if ($all_person_num > 0 && isset($join_record[$k]['person_num']) && $join_record[$k]['person_num']) {
                $percentage = bcdiv($join_record[$k]['person_num'], $all_person_num, 2) * 100;
            }
            $data[$k]['percentage'] = (string)$percentage;
            $data[$k]['is_selected'] = 0;
            if ((int)$tid === $k) {
                $data[$k]['is_selected'] = 1;
            }
            $data[$k]['tag'] = $v;
        }
        //获取问题
        $question = NewProductService::getNewProductWikiInfo($nid, 'question') ?: '';
        $res['person_total'] = $all_person_num;
        $res['question'] = $question;
        $res['list'] = array_values($data);
        return $this->setSuccess($res);
    }

}